<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业实现低成本数字化转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\repositories\energy;

use think\facade\Db;
use think\exception\ValidateException;
use app\common\repositories\BaseRepository;
use app\common\dao\energy\EnergyQrcodeDao;
use app\common\repositories\property\basic\PropertyBasicRepository;
use app\common\repositories\property\users\PropertyUsersLogRepository;

/**
 * Class EnergyQrcodeRepository
 *
 * @package app\common\repositories\energy
 * @mixin EnergyQrcodeDao
 */
class EnergyQrcodeRepository extends BaseRepository
{

    public function __construct(EnergyQrcodeDao $dao)
    {
        $this->dao = $dao;
    }


    /**
     * @param array $where
     * @param $page
     * @param $limit
     * @return array
     */
    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->order('id desc')
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['code_url'] = $this->getCodeUrl($v);
        }
        return compact('list', 'count');
    }


    public function addInfo($propertyId, $data, int $userId = 0)
    {
        Db::startTrans();
        try {
            $num = $data['num'] ?? 1;
            $len = $data['len'] ?? 14;
            $prefix = ($data['prefix_no'] ?? '') . date('ymd');
            $startNum = $data['start_num'] ?? 1;
            $insertData = [];
            // 设置长度 - 前缀长度 = 数字长度
            $numLength = $len - strlen($prefix);
            for ($i = 0; $i < $num; $i++) {
                $code = $prefix . str_pad($i + $startNum, $numLength, '0', STR_PAD_LEFT);
                $insertData[] = [
                    'property_id' => $propertyId,
                    'energy_code' => $code
                ];
            }
            $res = $this->dao->getSearch([])->limit(500)->insertAll($insertData);
            Db::commit();
            return $res;
        } catch (\Exception $e) {
            exception_log('二维码生成失败', $e);
            Db::rollback();
            $pattern = '/Integrity constraint violation: 1062 Duplicate entry \'(.*?)\' for key/';
            if (preg_match($pattern, $e->getMessage(), $matches)) {
                $duplicateEntry = $matches[1];
                throw new ValidateException($duplicateEntry . " 已重复，请重新调整生成");
            }
        }
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'SHARED.QRCODE.EDIT', $data);
            return $this->dao->update($info['id'], $data);
        });
    }

    public function batchDelete(array $ids, int $userId = 0)
    {
        $list = $this->dao->selectWhere([
            ['id', 'in', $ids], ['status', 'in', [2, 3]]
        ], 'id,property_id');
        if ($list) {
            foreach ($list as $k => $v) {
                $this->deleteInfo($v, $userId);
            }
            return $list;
        }
        return [];
    }

    /**
     *  删除二维码
     * @param $info
     * @param int $userId
     * @return mixed
     *
     * @author Amos
     * 2024-05-21 20:12
     */
    public function deleteInfo($info, int $userId = 0)
    {
        return Db::transaction(function () use ($info, $userId) {
            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'SHARED.QRCODE.DEL', $info);
            $this->dao->delete($info['id']);
        });
    }


    /**
     *  获取二维址链接地址
     * @param $qrcodeInfo
     * @return string
     *
     * @author Amos
     * 2024-05-31 11:17
     */
    public function getCodeUrl($info)
    {
        /** @var PropertyBasicRepository $repository */
        $repository = app()->make(PropertyBasicRepository::class);
        $propertyInfo = $repository->getConfig($info['property_id']);
        $domain = rtrim($propertyInfo['website'], '/');
        return $domain . '/qrcode/device_code?code=' . $info['energy_code'];
    }
}
